package com.rbac.controller;

import com.rbac.annotation.RequiresPermission;
import com.rbac.common.Result;
import com.rbac.dto.RoleQueryDTO;
import com.rbac.entity.SysRole;
import com.rbac.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/role")
@CrossOrigin
public class RoleController {
	
	@Autowired
	private RoleService roleService;
	
	@GetMapping("/list")
	@RequiresPermission("system:role:query")
	public Result<PageInfo> getRoleList(RoleQueryDTO queryDTO) {
		PageInfo roleList = roleService.getRoleList(queryDTO);
		return Result.success(roleList);
	}
	
	@GetMapping("/{id}")
	@RequiresPermission("system:role:query")
	public Result<SysRole> getRoleById(@PathVariable Long id) {
		SysRole role = roleService.getRoleById(id);
		if (role != null) {
			return Result.success(role);
		} else {
			return Result.error("角色不存在");
		}
	}
	
	@PostMapping
	@RequiresPermission("system:role:add")
	public Result<String> addRole(@Valid @RequestBody SysRole role) {
		boolean success = roleService.addRole(role);
		if (success) {
			return Result.success("新增角色成功");
		} else {
			return Result.error("新增角色失败，角色编码可能已存在");
		}
	}
	
	@PutMapping
	@RequiresPermission("system:role:edit")
	public Result<String> updateRole(@Valid @RequestBody SysRole role) {
		boolean success = roleService.updateRole(role);
		if (success) {
			return Result.success("更新角色成功");
		} else {
			return Result.error("更新角色失败");
		}
	}
	
	@DeleteMapping("/{id}")
	@RequiresPermission("system:role:delete")
	public Result<String> deleteRole(@PathVariable Long id) {
		boolean success = roleService.deleteRole(id);
		if (success) {
			return Result.success("删除角色成功");
		} else {
			return Result.error("删除角色失败");
		}
	}
	
	@PutMapping("/{id}/status")
	@RequiresPermission("system:role:edit")
	public Result<String> updateRoleStatus(@PathVariable Long id, @RequestParam Integer status) {
		boolean success = roleService.updateRoleStatus(id, status);
		if (success) {
			return Result.success("更新角色状态成功");
		} else {
			return Result.error("更新角色状态失败");
		}
	}
	
	// 查询角色已有权限ID
	@GetMapping("/{id}/permissions")
	@RequiresPermission("system:role:query")
	public Result<List<Long>> getRolePermissionIds(@PathVariable("id") Long roleId) {
		List<Long> ids = roleService.getPermissionIdsByRoleId(roleId);
		return Result.success(ids);
	}
	
	// 分配权限
	@PostMapping("/{id}/permissions")
	@RequiresPermission("system:role:edit")
	public Result<String> assignPermissions(@PathVariable("id") Long roleId, @RequestBody List<Long> permissionIds) {
		boolean ok = roleService.assignPermissions(roleId, permissionIds);
		return ok ? Result.success("分配权限成功") : Result.error("分配权限失败");
	}
} 